home *** CD-ROM | disk | FTP | other *** search
/ PC Open 102 / PC Open 102 CD 1.bin / CD1 / INTERNET / EMAIL / pop file / setup.exe / $_1_ / HTTP / Headers.pm < prev    next >
Encoding:
Perl POD Document  |  2004-02-03  |  18.1 KB  |  603 lines

  1. package HTTP::Headers;
  2.  
  3. # $Id: Headers.pm,v 1.47 2003/10/23 19:11:32 uid39246 Exp $
  4.  
  5. use strict;
  6. use Carp ();
  7.  
  8. use vars qw($VERSION $TRANSLATE_UNDERSCORE);
  9. $VERSION = sprintf("%d.%02d", q$Revision: 1.47 $ =~ /(\d+)\.(\d+)/);
  10.  
  11. # The $TRANSLATE_UNDERSCORE variable controls whether '_' can be used
  12. # as a replacement for '-' in header field names.
  13. $TRANSLATE_UNDERSCORE = 1 unless defined $TRANSLATE_UNDERSCORE;
  14.  
  15. # "Good Practice" order of HTTP message headers:
  16. #    - General-Headers
  17. #    - Request-Headers
  18. #    - Response-Headers
  19. #    - Entity-Headers
  20.  
  21. my @header_order = qw(
  22.    Cache-Control Connection Date Pragma Trailer Transfer-Encoding Upgrade
  23.    Via Warning
  24.  
  25.    Accept Accept-Charset Accept-Encoding Accept-Language
  26.    Authorization Expect From Host
  27.    If-Match If-Modified-Since If-None-Match If-Range If-Unmodified-Since
  28.    Max-Forwards Proxy-Authorization Range Referer TE User-Agent
  29.  
  30.    Accept-Ranges Age ETag Location Proxy-Authenticate Retry-After Server
  31.    Vary WWW-Authenticate
  32.  
  33.    Allow Content-Encoding Content-Language Content-Length Content-Location
  34.    Content-MD5 Content-Range Content-Type Expires Last-Modified
  35. );
  36.  
  37. # Make alternative representations of @header_order.  This is used
  38. # for sorting and case matching.
  39. my %header_order;
  40. my %standard_case;
  41.  
  42. {
  43.     my $i = 0;
  44.     for (@header_order) {
  45.     my $lc = lc $_;
  46.     $header_order{$lc} = ++$i;
  47.     $standard_case{$lc} = $_;
  48.     }
  49. }
  50.  
  51.  
  52.  
  53. sub new
  54. {
  55.     my($class) = shift;
  56.     my $self = bless {}, $class;
  57.     $self->header(@_); # set up initial headers
  58.     $self;
  59. }
  60.  
  61.  
  62. sub header
  63. {
  64.     my $self = shift;
  65.     my(@old);
  66.     while (my($field, $val) = splice(@_, 0, 2)) {
  67.     @old = $self->_header($field, $val);
  68.     }
  69.     return @old if wantarray;
  70.     return $old[0] if @old <= 1;
  71.     join(", ", @old);
  72. }
  73.  
  74.  
  75. sub push_header
  76. {
  77.     Carp::croak('Usage: $h->push_header($field, $val)') if @_ != 3;
  78.     shift->_header(@_, 'PUSH');
  79. }
  80.  
  81.  
  82. sub init_header
  83. {
  84.     Carp::croak('Usage: $h->init_header($field, $val)') if @_ != 3;
  85.     shift->_header(@_, 'INIT');
  86. }
  87.  
  88.  
  89. sub remove_header
  90. {
  91.     my($self, @fields) = @_;
  92.     my $field;
  93.     my @values;
  94.     foreach $field (@fields) {
  95.     $field =~ tr/_/-/ if $TRANSLATE_UNDERSCORE;
  96.     my $v = delete $self->{lc $field};
  97.     push(@values, ref($v) eq 'ARRAY' ? @$v : $v) if defined $v;
  98.     }
  99.     return @values;
  100. }
  101.  
  102.  
  103. sub _header
  104. {
  105.     my($self, $field, $val, $op) = @_;
  106.     $field =~ tr/_/-/ if $TRANSLATE_UNDERSCORE;
  107.  
  108.     # $push is only used interally sub push_header
  109.     Carp::croak('Need a field name') unless length($field);
  110.  
  111.     my $lc_field = lc $field;
  112.     unless(defined $standard_case{$lc_field}) {
  113.     # generate a %standard_case entry for this field
  114.     $field =~ s/\b(\w)/\u$1/g;
  115.     $standard_case{$lc_field} = $field;
  116.     }
  117.  
  118.     my $h = $self->{$lc_field};
  119.     my @old = ref($h) eq 'ARRAY' ? @$h : (defined($h) ? ($h) : ());
  120.  
  121.     $op ||= "";
  122.     $val = undef if $op eq 'INIT' && @old;
  123.     if (defined($val)) {
  124.     my @new = ($op eq 'PUSH') ? @old : ();
  125.     if (ref($val) ne 'ARRAY') {
  126.         push(@new, $val);
  127.     }
  128.     else {
  129.         push(@new, @$val);
  130.     }
  131.     $self->{$lc_field} = @new > 1 ? \@new : $new[0];
  132.     }
  133.     @old;
  134. }
  135.  
  136.  
  137. # Compare function which makes it easy to sort headers in the
  138. # recommended "Good Practice" order.
  139. sub _header_cmp
  140. {
  141.     ($header_order{$a} || 999) <=> ($header_order{$b} || 999) || $a cmp $b;
  142. }
  143.  
  144.  
  145. sub scan
  146. {
  147.     my($self, $sub) = @_;
  148.     my $key;
  149.     foreach $key (sort _header_cmp keys %$self) {
  150.         next if $key =~ /^_/;
  151.     my $vals = $self->{$key};
  152.     if (ref($vals) eq 'ARRAY') {
  153.         my $val;
  154.         for $val (@$vals) {
  155.         &$sub($standard_case{$key} || $key, $val);
  156.         }
  157.     }
  158.     else {
  159.         &$sub($standard_case{$key} || $key, $vals);
  160.     }
  161.     }
  162. }
  163.  
  164.  
  165. sub as_string
  166. {
  167.     my($self, $endl) = @_;
  168.     $endl = "\n" unless defined $endl;
  169.  
  170.     my @result = ();
  171.     $self->scan(sub {
  172.     my($field, $val) = @_;
  173.     if ($val =~ /\n/) {
  174.         # must handle header values with embedded newlines with care
  175.         $val =~ s/\s+$//;          # trailing newlines and space must go
  176.         $val =~ s/\n\n+/\n/g;      # no empty lines
  177.         $val =~ s/\n([^\040\t])/\n $1/g;  # intial space for continuation
  178.         $val =~ s/\n/$endl/g;      # substitute with requested line ending
  179.     }
  180.     push(@result, "$field: $val");
  181.     });
  182.  
  183.     join($endl, @result, '');
  184. }
  185.  
  186.  
  187. sub clone
  188. {
  189.     my $self = shift;
  190.     my $clone = new HTTP::Headers;
  191.     $self->scan(sub { $clone->push_header(@_);} );
  192.     $clone;
  193. }
  194.  
  195.  
  196. sub _date_header
  197. {
  198.     require HTTP::Date;
  199.     my($self, $header, $time) = @_;
  200.     my($old) = $self->_header($header);
  201.     if (defined $time) {
  202.     $self->_header($header, HTTP::Date::time2str($time));
  203.     }
  204.     HTTP::Date::str2time($old);
  205. }
  206.  
  207.  
  208. sub date                { shift->_date_header('Date',                @_); }
  209. sub expires             { shift->_date_header('Expires',             @_); }
  210. sub if_modified_since   { shift->_date_header('If-Modified-Since',   @_); }
  211. sub if_unmodified_since { shift->_date_header('If-Unmodified-Since', @_); }
  212. sub last_modified       { shift->_date_header('Last-Modified',       @_); }
  213.  
  214. # This is used as a private LWP extention.  The Client-Date header is
  215. # added as a timestamp to a response when it has been received.
  216. sub client_date         { shift->_date_header('Client-Date',         @_); }
  217.  
  218. # The retry_after field is dual format (can also be a expressed as
  219. # number of seconds from now), so we don't provide an easy way to
  220. # access it until we have know how both these interfaces can be
  221. # addressed.  One possibility is to return a negative value for
  222. # relative seconds and a positive value for epoch based time values.
  223. #sub retry_after       { shift->_date_header('Retry-After',       @_); }
  224.  
  225. sub content_type      {
  226.   my $ct = (shift->_header('Content-Type', @_))[0];
  227.   return '' unless defined($ct) && length($ct);
  228.   my @ct = split(/\s*;\s*/, lc($ct));
  229.   wantarray ? @ct : $ct[0];
  230. }
  231.  
  232. sub title             { (shift->_header('Title',            @_))[0] }
  233. sub content_encoding  { (shift->_header('Content-Encoding', @_))[0] }
  234. sub content_language  { (shift->_header('Content-Language', @_))[0] }
  235. sub content_length    { (shift->_header('Content-Length',   @_))[0] }
  236.  
  237. sub user_agent        { (shift->_header('User-Agent',       @_))[0] }
  238. sub server            { (shift->_header('Server',           @_))[0] }
  239.  
  240. sub from              { (shift->_header('From',             @_))[0] }
  241. sub referer           { (shift->_header('Referer',          @_))[0] }
  242. *referrer = \&referer;  # on tchrist's request
  243. sub warning           { (shift->_header('Warning',          @_))[0] }
  244.  
  245. sub www_authenticate  { (shift->_header('WWW-Authenticate', @_))[0] }
  246. sub authorization     { (shift->_header('Authorization',    @_))[0] }
  247.  
  248. sub proxy_authenticate  { (shift->_header('Proxy-Authenticate',  @_))[0] }
  249. sub proxy_authorization { (shift->_header('Proxy-Authorization', @_))[0] }
  250.  
  251. sub authorization_basic       { shift->_basic_auth("Authorization",       @_) }
  252. sub proxy_authorization_basic { shift->_basic_auth("Proxy-Authorization", @_) }
  253.  
  254. sub _basic_auth {
  255.     require MIME::Base64;
  256.     my($self, $h, $user, $passwd) = @_;
  257.     my($old) = $self->_header($h);
  258.     if (defined $user) {
  259.     Carp::croak("Basic authorization user name can't contain ':'")
  260.       if $user =~ /:/;
  261.     $passwd = '' unless defined $passwd;
  262.     $self->_header($h => 'Basic ' .
  263.                              MIME::Base64::encode("$user:$passwd", ''));
  264.     }
  265.     if (defined $old && $old =~ s/^\s*Basic\s+//) {
  266.     my $val = MIME::Base64::decode($old);
  267.     return $val unless wantarray;
  268.     return split(/:/, $val, 2);
  269.     }
  270.     return;
  271. }
  272.  
  273.  
  274. 1;
  275.  
  276. __END__
  277.  
  278. =head1 NAME
  279.  
  280. HTTP::Headers - Class encapsulating HTTP Message headers
  281.  
  282. =head1 SYNOPSIS
  283.  
  284.  require HTTP::Headers;
  285.  $h = HTTP::Headers->new;
  286.  
  287.  $h->header('Content-Type' => 'text/plain');  # set
  288.  $ct = $h->header('Content-Type');            # get
  289.  $h->remove_header('Content-Type');           # delete
  290.  
  291. =head1 DESCRIPTION
  292.  
  293. The C<HTTP::Headers> class encapsulates HTTP-style message headers.
  294. The headers consist of attribute-value pairs also called fields, which
  295. may be repeated, and which are printed in a particular order.
  296.  
  297. Instances of this class are usually created as member variables of the
  298. C<HTTP::Request> and C<HTTP::Response> classes, internal to the
  299. library.
  300.  
  301. The following methods are available:
  302.  
  303. =over 4
  304.  
  305. =item $h = HTTP::Headers->new
  306.  
  307. Constructs a new C<HTTP::Headers> object.  You might pass some initial
  308. attribute-value pairs as parameters to the constructor.  I<E.g.>:
  309.  
  310.  $h = HTTP::Headers->new(
  311.        Date         => 'Thu, 03 Feb 1994 00:00:00 GMT',
  312.        Content_Type => 'text/html; version=3.2',
  313.        Content_Base => 'http://www.perl.org/');
  314.  
  315. The constructor arguments are passed to the C<header> method which is
  316. described below.
  317.  
  318. =item $h->header( $field )
  319.  
  320. =item $h->header( $field => $value, ... )
  321.  
  322. Get or set the value of one or more header fields.  The header field name
  323. ($field) is not case sensitive.  To make the life easier for perl
  324. users who wants to avoid quoting before the => operator, you can use
  325. '_' as a replacement for '-' in header names (this behaviour can be
  326. suppressed by setting the $HTTP::Headers::TRANSLATE_UNDERSCORE
  327. variable to a FALSE value).
  328.  
  329. The header() method accepts multiple ($field => $value) pairs, which
  330. means that you can update several fields with a single invocation.
  331.  
  332. The $value argument may be a plain string or a reference to an array
  333. of strings for a multi-valued field. If the $value is undefined or not
  334. given, then that header field will remain unchanged.
  335.  
  336. The old value (or values) of the last of the header fields is returned.
  337. If no such field exists C<undef> will be returned.
  338.  
  339. A multi-valued field will be retuned as separate values in list
  340. context and will be concatenated with ", " as separator in scalar
  341. context.  The HTTP spec (RFC 2616) promise that joining multiple
  342. values in this way will not change the semantic of a header field, but
  343. in practice there are cases like old-style Netscape cookies (see
  344. L<HTTP::Cookies>) where "," is used as part of the syntax of a single
  345. field value.
  346.  
  347. Examples:
  348.  
  349.  $header->header(MIME_Version => '1.0',
  350.          User_Agent   => 'My-Web-Client/0.01');
  351.  $header->header(Accept => "text/html, text/plain, image/*");
  352.  $header->header(Accept => [qw(text/html text/plain image/*)]);
  353.  @accepts = $header->header('Accept');  # get multiple values
  354.  $accepts = $header->header('Accept');  # get values as a single string
  355.  
  356. =item $h->push_header( $field => $value )
  357.  
  358. Add a new field value for the specified header field.  Previous values
  359. for the same field are retained.
  360.  
  361. As for the header() method, the field name ($field) is not case
  362. sensitive and '_' can be used as a replacement for '-'.
  363.  
  364. The $value argument may be a scalar or a reference to a list of
  365. scalars.
  366.  
  367.  $header->push_header(Accept => 'image/jpeg');
  368.  $header->push_header(Accept => [map "image/$_", qw(gif png tiff)]);
  369.  
  370. =item $h->init_header( $field => $value )
  371.  
  372. Set the specified header to the given value, but only if no previous
  373. value for that field is set.
  374.  
  375. The header field name ($field) is not case sensitive and '_'
  376. can be used as a replacement for '-'.
  377.  
  378. The $value argument may be a scalar or a reference to a list of
  379. scalars.
  380.  
  381. =item $h->remove_header( $field, ... )
  382.  
  383. This function removes the headers fields with the specified names.
  384.  
  385. The header field names ($field) are not case sensitive and '_'
  386. can be used as a replacement for '-'.
  387.  
  388. The return value is the values of the fields removed.  In scalar
  389. context the number of fields removed is returned.
  390.  
  391. Note that if you pass in multiple field names then it is generally not
  392. possible to tell which of the returned values belonged to which field.
  393.  
  394. =item $h->scan( \&process_header_field )
  395.  
  396. Apply a subroutine to each header field in turn.  The callback routine
  397. is called with two parameters; the name of the field and a single
  398. value (a string).  If a header field is multi-valued, then the
  399. routine is called once for each value.  The field name passed to the
  400. callback routine has case as suggested by HTTP spec, and the headers
  401. will be visited in the recommended "Good Practice" order.
  402.  
  403. Any return values of the callback routine are ignored.  The loop can
  404. be broken by raising an exception (C<die>).
  405.  
  406. =item $h->as_string
  407.  
  408. =item $h->as_string( $endl )
  409.  
  410. Return the header fields as a formatted MIME header.  Since it
  411. internally uses the C<scan> method to build the string, the result
  412. will use case as suggested by HTTP spec, and it will follow
  413. recommended "Good Practice" of ordering the header fieds.  Long header
  414. values are not folded.
  415.  
  416. The optional $endl parameter specifies the line ending sequence to
  417. use.  The default is "\n".  Embedded "\n" characters in header field
  418. values will be substitued with this line ending sequence.
  419.  
  420. =item $h->clone
  421.  
  422. Returns a copy of this C<HTTP::Headers> object.
  423.  
  424. =back
  425.  
  426. =head1 CONVENIENCE METHODS
  427.  
  428. The most frequently used headers can also be accessed through the
  429. following convenience methods.  These methods can both be used to read
  430. and to set the value of a header.  The header value is set if you pass
  431. an argument to the method.  The old header value is always returned.
  432. If the given header did not exists then C<undef> is returned.
  433.  
  434. Methods that deal with dates/times always convert their value to system
  435. time (seconds since Jan 1, 1970) and they also expect this kind of
  436. value when the header value is set.
  437.  
  438. =over 4
  439.  
  440. =item $h->date
  441.  
  442. This header represents the date and time at which the message was
  443. originated. I<E.g.>:
  444.  
  445.   $h->date(time);  # set current date
  446.  
  447. =item $h->expires
  448.  
  449. This header gives the date and time after which the entity should be
  450. considered stale.
  451.  
  452. =item $h->if_modified_since
  453.  
  454. =item $h->if_unmodified_since
  455.  
  456. These header fields are used to make a request conditional.  If the requested
  457. resource has (or has not) been modified since the time specified in this field,
  458. then the server will return a C<304 Not Modified> response instead of
  459. the document itself.
  460.  
  461. =item $h->last_modified
  462.  
  463. This header indicates the date and time at which the resource was last
  464. modified. I<E.g.>:
  465.  
  466.   # check if document is more than 1 hour old
  467.   if (my $last_mod = $h->last_modified) {
  468.       if ($last_mod < time - 60*60) {
  469.       ...
  470.       }
  471.   }
  472.  
  473. =item $h->content_type
  474.  
  475. The Content-Type header field indicates the media type of the message
  476. content. I<E.g.>:
  477.  
  478.   $h->content_type('text/html');
  479.  
  480. The value returned will be converted to lower case, and potential
  481. parameters will be chopped off and returned as a separate value if in
  482. an array context.  This makes it safe to do the following:
  483.  
  484.   if ($h->content_type eq 'text/html') {
  485.      # we enter this place even if the real header value happens to
  486.      # be 'TEXT/HTML; version=3.0'
  487.      ...
  488.   }
  489.  
  490. =item $h->content_encoding
  491.  
  492. The Content-Encoding header field is used as a modifier to the
  493. media type.  When present, its value indicates what additional
  494. encoding mechanism has been applied to the resource.
  495.  
  496. =item $h->content_length
  497.  
  498. A decimal number indicating the size in bytes of the message content.
  499.  
  500. =item $h->content_language
  501.  
  502. The natural language(s) of the intended audience for the message
  503. content.  The value is one or more language tags as defined by RFC
  504. 1766.  Eg. "no" for some kind of Norwegian and "en-US" for English the
  505. way it is written in the US.
  506.  
  507. =item $h->title
  508.  
  509. The title of the document.  In libwww-perl this header will be
  510. initialized automatically from the E<lt>TITLE>...E<lt>/TITLE> element
  511. of HTML documents.  I<This header is no longer part of the HTTP
  512. standard.>
  513.  
  514. =item $h->user_agent
  515.  
  516. This header field is used in request messages and contains information
  517. about the user agent originating the request.  I<E.g.>:
  518.  
  519.   $h->user_agent('Mozilla/1.2');
  520.  
  521. =item $h->server
  522.  
  523. The server header field contains information about the software being
  524. used by the originating server program handling the request.
  525.  
  526. =item $h->from
  527.  
  528. This header should contain an Internet e-mail address for the human
  529. user who controls the requesting user agent.  The address should be
  530. machine-usable, as defined by RFC822.  E.g.:
  531.  
  532.   $h->from('King Kong <king@kong.com>');
  533.  
  534. I<This header is no longer part of the HTTP standard.>
  535.  
  536. =item $h->referer
  537.  
  538. Used to specify the address (URI) of the document from which the
  539. requested resouce address was obtained.
  540.  
  541. The "Free On-line Dictionary of Computing" as this to say about the
  542. word I<referer>:
  543.  
  544.      <World-Wide Web> A misspelling of "referrer" which
  545.      somehow made it into the {HTTP} standard.  A given {web
  546.      page}'s referer (sic) is the {URL} of whatever web page
  547.      contains the link that the user followed to the current
  548.      page.  Most browsers pass this information as part of a
  549.      request.
  550.  
  551.      (1998-10-19)
  552.  
  553. By popular demand C<referrer> exists as an alias for this method so you
  554. can avoid this misspelling in your programs and still send the right
  555. thing on the wire.
  556.  
  557.  
  558. =item $h->www_authenticate
  559.  
  560. This header must be included as part of a C<401 Unauthorized> response.
  561. The field value consist of a challenge that indicates the
  562. authentication scheme and parameters applicable to the requested URI.
  563.  
  564. =item $h->proxy_authenticate
  565.  
  566. This header must be included in a C<407 Proxy Authentication Required>
  567. response.
  568.  
  569. =item $h->authorization
  570.  
  571. =item $h->proxy_authorization
  572.  
  573. A user agent that wishes to authenticate itself with a server or a
  574. proxy, may do so by including these headers.
  575.  
  576. =item $h->authorization_basic
  577.  
  578. This method is used to get or set an authorization header that use the
  579. "Basic Authentication Scheme".  In array context it will return two
  580. values; the user name and the password.  In scalar context it will
  581. return I<"uname:password"> as a single string value.
  582.  
  583. When used to set the header value, it expects two arguments.  I<E.g.>:
  584.  
  585.   $h->authorization_basic($uname, $password);
  586.  
  587. The method will croak if the $uname contains a colon ':'.
  588.  
  589. =item $h->proxy_authorization_basic
  590.  
  591. Same as authorization_basic() but will set the "Proxy-Authorization"
  592. header instead.
  593.  
  594. =back
  595.  
  596. =head1 COPYRIGHT
  597.  
  598. Copyright 1995-2002 Gisle Aas.
  599.  
  600. This library is free software; you can redistribute it and/or
  601. modify it under the same terms as Perl itself.
  602.  
  603.